package com.hzl.lease.web.admin.custom.interceptor;

import com.hzl.lease.common.context.LoginUser;
import com.hzl.lease.common.context.LoginUserContext;
import com.hzl.lease.common.exception.LeaseException;
import com.hzl.lease.common.result.ResultCodeEnum;
import com.hzl.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
//拦截器功能，拦截到控制层controller的请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access_token");  //根据请求获取请求头，条件字段（access_token）
        if(token==null){             //如果token为空，抛出异常
            throw  new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else{
            //否则解析token
            Claims claims = JwtUtil.parseToken(token);

            Long userId = claims.get("userId", Long.class);
            String userName = claims.get("userName", String.class);

               /*request.setAttribute("userId", userId);
               request.setAttribute("userName", userName);*/

            //把token中的信息保存到ThreadLocal中
           LoginUserContext.set(new LoginUser(userId,userName));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //删除请求域中的数据
        /*request.removeAttribute("userId");
        request.removeAttribute("userName");*/

        //删除ThreadLocal中的数据
    LoginUserContext.remove();
    }
}